package com.yq.cp.config;
import com.alibaba.fastjson.JSONObject;
import com.yq.cp.entity.permission.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;

@Slf4j
@Component
public class TransmitUserInfoFilter implements Filter {

    public TransmitUserInfoFilter() {
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        this.initUserInfo((HttpServletRequest)request);
        chain.doFilter(request,response);
    }

    private void initUserInfo(HttpServletRequest request){
        String userJson = request.getHeader("tokenInfo");
//        log.info("接收用户信息:"+userJson);
        if (StringUtils.isNotBlank(userJson)) {
            try {
                userJson = URLDecoder.decode(userJson,"UTF-8");
                User user = JSONObject.parseObject(userJson,User.class);
                //将UserInfo放入上下文中
                UserThreadLocal.put(user);
            } catch (Exception e) {
                log.error("init userInfo error",e);
            }
        }
    }
}
